import React from 'react';
import { getformjsonbytemplateid, getformjsonbyformtemplateid } from '@/services/flowMine/apply';
// import zpxu from '@/components/JsonForm/mock/recruitmentNeeds.json';
import {
    addGradeType,
    addGrade,
    editGradeType,
    editGrade,
    deleteGrade,
    deleteGradeType,
    editSalary,
    positionMapping
} from '../customData';
import modifyJson from '../modifyJson';

const COUNTRY_TYPE_MAP = {
    xiamen: 'China',
    shenzhen: 'China',
    singapore: 'Singapore'
};
// 注意：职级从本地获取配置文件，需要确定服务端 templateId 是否固定
const localFormJson = {
    49: addGradeType,
    52: addGrade,
    50: editGradeType,
    53: editGrade,
    51: deleteGradeType,
    54: deleteGrade,
    55: editSalary,
    58: positionMapping
};

const defaultJson = { key: 'xiamen', description: '', fields: [] };

/**
 * 获取动态表单 JSON 配置
 */
const useFormJson = ({
    templateId,
    applicationNo,
    formDeploymentId,
    form,
    onlyShowForm,
    restQuery,
    currentUser,
    setTakeUsers,
    setPostList,
    setLeaders,
    setRecorder,
    fetching,
    setFetching,
    setOriginInstitutionName
}) => {
    const [json, setJson] = React.useState(defaultJson);
    const [loading, setLoading] = React.useState(true);

    React.useEffect(() => {
        const fetchJson = async () => {
            let result = {};
            if (!applicationNo) {
                result = await getformjsonbytemplateid(templateId);
            } else {
                result = await getformjsonbyformtemplateid(formDeploymentId);
            }

            if (result.code === 10000) {
                console.log('===============================================>调试 动态表单服务端数据', result.data);
                const [keyPrefix] = result.data.key.split('-');
                const COUNTRY = COUNTRY_TYPE_MAP[keyPrefix] === 'China' ? 'zh' : 'sg'; // 国家，目前只支持 zh 和 sg

                // 注意：仅当服务端
                const resultJson = await modifyJson({
                    json: localFormJson[templateId] || result.data || defaultJson,
                    country: COUNTRY,
                    form,
                    onlyShowForm,
                    restQuery,
                    currentUser,
                    setTakeUsers,
                    setLeaders,
                    setPostList,
                    setRecorder,
                    fetching,
                    setFetching,
                    setOriginInstitutionName
                });
                console.log('===============================================>调试 modifyJson 执行结果', resultJson);
                setJson(resultJson);
            }

            setLoading(false);
        };

        fetchJson();
    }, [getformjsonbytemplateid, templateId, applicationNo, formDeploymentId]);

    return [loading, json, setJson];
};

export default useFormJson;
